const citySelector = requirePlugin('citySelector');
import Dialog from '@vant/weapp/dialog/dialog';
const myRequest = require('../../../../utils/request'); // 导入整个模块
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    navBarHeight: 0,
    latitude: 0,
    longitude: 0,
    paneltop: 425,
    grouplist: [],
    activeindex: 0,
    updateshow: false,
    isfocus: false,
    // 移动块的id
    moveId: null,
    // 最终停止的位置
    endY: 0,
    item: {},
    addnewplaceshow: false,
    newcity: '不限',
    searchplace: '',
    searchlist: [],
    polyline: [],
    placelist: [],
    placelistheight: '40%',
    actionshow: false,
    updateindex: 0,
    actions: [{
        name: '导航',
      },
      {
        name: '删除',
        color: '#ee0a24'
      },

    ],
    markers: [],
    date: '',
    username: '',
    name: '',
    nameshow: false
  },
  savename() {
    if (!this.data.name) return wx.showToast({
      title: '行程名暂未填写！',
      icon: 'error'
    })

    let that = this
    let data = {
      date: this.data.item.date ? this.data.item.date : this.data.date,
      projectlist: JSON.stringify(this.data.grouplist),
      username: this.data.username,
      name: this.data.name,
      id: this.data.item.id ? this.data.item.id : ''
    }
    let url = this.data.item.id ? '/project/update' : '/project/add'
    myRequest.post(url, data).then(res => {
      wx.showToast({
        title: !that.data.item.id ? '添加成功！' : '更新成功!',
        icon: 'success'
      })
      setTimeout(() => {
        that.goback()

      }, 1000);
    })

  },
  onClosename() {
    this.setData({
      nameshow: false
    })
  },
  save() {
    this.setData({
      nameshow: true
    })

  },
  onnameChange(event) {
    this.setData({
      name: event.detail
    })
  },

  updatewirte(e) {
    console.log(e);
    this.setData({
      actionshow: true,
      updateindex: e.currentTarget.dataset.index
    })
  },
  onactionClose() {
    this.setData({
      actionshow: false
    })
  },
  onSelect(e) {
    // console.log(e);
    if (e.detail.name == '删除') {
      const data = [...this.data.grouplist]
      data[this.data.activeindex].locationlist.splice(this.data.updateindex, 1)
      this.setData({
        grouplist: data,
        placelist: data[this.data.activeindex].locationlist
      })
      this.getpolyline()
      this.getmarkers()
      this.changeview()

    } else {
      let latitude = this.data.grouplist[this.data.activeindex].locationlist[this.data.updateindex].location.lat
      let longitude = this.data.grouplist[this.data.activeindex].locationlist[this.data.updateindex].location.lng
      let title = this.data.grouplist[this.data.activeindex].locationlist[this.data.updateindex].title
      wx.openLocation({
        latitude,
        longitude,
        name: title,
        scale: 15
      })
    }
  },
  switchplace(e) {
    const data = [...this.data.grouplist]
    data[this.data.activeindex].locationlist.push(e.currentTarget.dataset.item)
    this.setData({
      grouplist: data,
      addnewplaceshow: false,
      searchplace: '',
      searchlist: [],
      placelist: data[this.data.activeindex].locationlist
    })
    this.getpolyline()
    this.getmarkers()
    this.initplace(this.data.placelist)

    this.changeview()
  },
  getpolyline() {
    let data = []
    this.data.grouplist[this.data.activeindex]?.locationlist.forEach(val => {
      data.push({
        latitude: val.location.lat,
        longitude: val.location.lng,
      })
    })
    let ploy = []
    ploy.push({
      points: data,
      color: '#81D388',
      width: 6,
      borderColor: '#2b90d9',
      borderWidth: 2
    })
    this.setData({
      polyline: ploy
    })
  },
  getmarkers() {


    const data = []
    this.data.grouplist[this.data.activeindex]?.locationlist.forEach(val => {
      data.push({
        id: data.length,
        latitude: val.location.lat,
        longitude: val.location.lng,
        width: 30,
        height: 30
      })
    })
    if (!data.length) {
      data.push({
        id: data.length,
        width: 30,
        height: 30,
        latitude: this.data.latitude,
        longitude: this.data.longitude
      })

    }
    this.setData({
      markers: data
    })
  },
  searchplacechange(e) {
    this.setData({
      searchplace: e.detail.value
    })
    let self = this
    // 如果已经存在定时器，则清除
    if (this.timeout) {
      clearTimeout(this.timeout);
    }

    // 设置定时器，延迟执行函数
    this.timeout = setTimeout(() => {
      // 这里放置需要节流执行的函数
      console.log('用户停止输入，执行函数', self.data.searchplace);
      //发起请求，执行关键词搜索
      self.gosearch()

    }, 1000); // 延迟时间可以根据需要调整，这里设置为1000毫秒
  },
  gosearch() {
    let that = this
    let url = ''
    if (this.data.newcity != '不限') {
      url = `https://apis.map.qq.com/ws/place/v1/suggestion/?region=${this.data.newcity}&keyword=${this.data.searchplace}&key=M54BZ-LTIW3-KEG3N-O245R-BVE52-EIBEX`
    } else {
      url = `https://apis.map.qq.com/ws/place/v1/suggestion/?keyword=${this.data.searchplace}&key=M54BZ-LTIW3-KEG3N-O245R-BVE52-EIBEX`
    }
    wx.request({
      url,
      method: 'GET',
      success(res) {
        if (!res.data.status) {
          that.setData({
            searchlist: res.data.data
          })
        }
      }
    })
  },
  switchcity() {
    const key = 'M54BZ-LTIW3-KEG3N-O245R-BVE52-EIBEX'; // 使用在腾讯位置服务申请的key
    const referer = 'wx63ffb7b7894e99ae'; // 调用插件的app的名称
    wx.navigateTo({
      url: `plugin://citySelector/index?key=${key}&referer=${referer}`,
    })
  },
  addnewplace() {
    console.log(this.data.grouplist[this.data.activeindex].locationlist.length);
    if (this.data.grouplist[this.data.activeindex].locationlist.length >= 8) {
      Dialog.alert({
        message: '当前地点超过8个，无法再次添加！',
      }).then(() => {
        // on close
      });
    } else {
      this.setData({
        addnewplaceshow: true
      })
    }

  },
  onCloseaddnew() {
    this.setData({
      addnewplaceshow: false
    })
  },
  goback() {
    wx.navigateBack();
  },
  async getplace() {
    const res = await wx.getLocation()
    let {
      longitude,
      latitude
    } = res;
    this.setData({
      longitude,
      latitude,

    })
  },

  changeview() {
    const mapCtx = wx.createMapContext('map'); //创建初始地图
    let includePointsData = []
    for (let i = 0; i < this.data.markers.length; i++) {
      includePointsData.push({
        latitude: this.data.markers[i].latitude,
        longitude: this.data.markers[i].longitude
      })
    }
    console.log(111, includePointsData);


    // console.log(includePointsData);
    // 显示所有标记点
    mapCtx.includePoints({
      padding: [100, 80, 100, 80],
      points: includePointsData //放入所有坐标轴的数组   并引用此方法
    })
  },

  handleCustomEvent: function (e) {
    this.setData({
      paneltop: e.detail + 125,
      placelistheight: !e.detail ? '80%' : '40%'
    })
  },
  switchtitle(e) {
    this.setData({
      activeindex: e.target.dataset.index,
      placelist: this.data.grouplist[e.target.dataset.index].locationlist
    })
    this.getplace()
    this.getmarkers()
    this.changeview()
    this.getpolyline()
    this.initplace(this.data.placelist)
  },
  updatetitle() {
    this.setData({
      updateshow: true
    })
  },
  onClose() {
    this.setData({
      updateshow: false
    })
  },
  delete(e) {
    if (this.data.grouplist.length == 1) return wx.showToast({
      title: '天数不能小于0！',
      icon: 'error'
    })
    const array = [...this.data.grouplist]
    array.splice(e.currentTarget.dataset.index, 1);
    this.setData({
      grouplist: array
    })
  },
  // 重置列表顺序
  init(grouplist) {
    // 列表项高度
    const ITEM_HEIGHT = 40
    // 列表项上外边距
    const ITEM_MARGIN_TOP = 15
    let newgrouplist = grouplist.map((item, index) => {
      item.id = index
      // 重置单项的y坐标(组件默认是绝对定位 left:0  top:0 )
      item.y = (ITEM_HEIGHT + ITEM_MARGIN_TOP) * index + ITEM_MARGIN_TOP
      return item
    })

    this.setData({
      grouplist: newgrouplist
    })
  },
  // 移动中-获取移动元素的id,实时获取移动元素的y坐标
  moving(e) {
    this.setData({
      moveId: e.currentTarget.dataset.moveid,
      endY: e.detail.y,
    })
  },
  // 移动后
  moved() {
    let {
      grouplist,
      moveId,
      endY
    } = this.data
    let newgrouplist = JSON.parse(JSON.stringify(grouplist))
    if (!moveId) return
    newgrouplist[moveId].y = endY
    newgrouplist = newgrouplist.sort((a, b) => a.y - b.y)
    this.init(newgrouplist)
  },

  // 重置列表顺序
  initplace(grouplist) {
    // 列表项高度
    const ITEM_HEIGHT = 40
    // 列表项上外边距
    const ITEM_MARGIN_TOP = 15
    let newgrouplist = grouplist.map((item, index) => {
      item.id = index
      // 重置单项的y坐标(组件默认是绝对定位 left:0  top:0 )
      item.y = (ITEM_HEIGHT + ITEM_MARGIN_TOP) * index + ITEM_MARGIN_TOP
      return item
    })

    this.setData({
      placelist: newgrouplist
    })
  },
  // 移动中-获取移动元素的id,实时获取移动元素的y坐标
  movingpalce(e) {
    this.setData({
      moveId: e.currentTarget.dataset.moveid,
      endY: e.detail.y,
    })
  },
  // 移动后
  movedplace() {
    let {
      placelist,
      moveId,
      endY
    } = this.data
    let newgrouplist = JSON.parse(JSON.stringify(placelist))
    if (!moveId) return
    newgrouplist[moveId].y = endY
    newgrouplist = newgrouplist.sort((a, b) => a.y - b.y)
    this.initplace(newgrouplist)
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    console.log(options);
    const sysInfo = wx.getSystemInfoSync();
    const data = []
    data.push({
      title: '分组一',
      locationlist: []
    })

    this.setData({
      navBarHeight: sysInfo.statusBarHeight,
      grouplist: options.item ? JSON.parse(options.item).projectlist : data,
      placelist: options.item ? JSON.parse(options.item).projectlist[this.data.activeindex].locationlist : data[this.data.activeindex].locationlist,
      date: options.date ? options.date : '',
      item: options.item ? JSON.parse(options.item) : {},
      username: JSON.parse(wx.getStorageSync('userinfo')).username,
      name: options.item ? JSON.parse(options.item).name : ''
    });
    this.mapchange()
    this.init(this.data.grouplist)
    this.initplace(this.data.placelist)
  },
  async mapchange() {
    try {
      await this.getplace()
      this.getmarkers()
      this.getpolyline()
      this.changeview()
    } catch (error) {

    }
  },
  inputchange(e) {
    console.log(e);
    const data = [...this.data.grouplist]
    data[e.currentTarget.dataset.index].title = e.detail.value
    this.setData({
      grouplist: data
    })
  },

  //新增分组
  addgroup() {
    if (this.data.grouplist.length >= 4) {
      return wx.showToast({
        title: '当前已超过四个分组，不可再添加',
        icon: 'error'
      })
    }

    const data = [...this.data.grouplist]
    data.push({
      title: '分组',
      locationlist: []
    })
    this.setData({
      grouplist: data
    })
    this.init(this.data.grouplist)

  },

  // 从城市选择器插件返回后，在页面的onShow生命周期函数中能够调用插件接口，获取cityInfo结果对象
  onShow() {
    if (citySelector.getCity())
      this.setData({
        newcity: citySelector.getCity().name,

      })
  },
  onUnload() {
    // 页面卸载时清空插件数据，防止再次进入页面，getCity返回的是上次的结果
    citySelector.clearCity();
  }
})